<template>
  <div class="container">
    <div class="courses">
      <h6>{{ homeworkDetail.homeworkTitle }}</h6>
      <div class="practice-details">
        <div class="practice-content">
          <p>{{ homeworkDetail.homeworkContent }}</p>
          <div class="time">
            <van-icon name="clock" /><span>{{ homeworkDetail.homeworkDeadline }}</span>
            <van-icon name="user" /><span>{{ homeworkDetail.teacherName }}</span>
          </div>
        </div>
      </div>
      <div class="example-video">
        <span class="label">示范视频/图片</span>
        <video
          v-if="
            getFileType(homeworkDetail.homeworkFilepath) == 'video' ||
            getFileType(homeworkDetail.homeworkFilepath) == 'audio'
          "
          controls
          width="100%"
        >
          <source :src="homeworkDetail.homeworkFilepath" type="video/mp4" />
        </video>
        <van-image
          v-else-if="getFileType(homeworkDetail.homeworkFilepath) == 'image'"
          width="100%"
          height="200px"
          fit="cover"
          :src="homeworkDetail.homeworkFilepath"
        />
        <!-- <div class="video-tip">点击播放示范视频</div> -->
      </div>
    </div>

    <div class="activity">
      <h6>提交内容</h6>
      <div class="video-upload">
        <div class="upload-title">
          <span class="label">训练视频</span>
          <div class="video-actions">
            <van-button
              :class="activeBtn == 'original' ? 'active-btn' : ''"
              size="mini"
              @click="showOriginal"
              >原视频</van-button
            >
            <van-button
              :class="activeBtn == 'analyze' ? 'active-btn' : ''"
              size="mini"
              @click="analyzeVideo"
              >AI解析</van-button
            >
          </div>
        </div>

        <!-- 上传后显示视频 -->
        <div v-if="videoUrl && activeBtn == 'original'" class="upload-container">
          <van-icon v-if="homeworkDetail.homeworkFlag !== '2'" name="cross" @click="deleteFile" />
          <video controls :src="videoUrl" style="max-width: 100%; margin-top: 16px"></video>
        </div>
        <div v-if="!videoUrl">
          <van-uploader
            v-model="videoFile"
            :after-read="onUploadVideo"
            :preview-image="false"
            accept="video/*"
            :max-count="1"
            upload-text="点击选择视频"
          />
        </div>
        <div v-if="analysisResult.analysisVideo && activeBtn == 'analyze'" class="upload-container">
          <video
            controls
            :src="analysisResult.analysisVideo"
            style="max-width: 100%; margin-top: 16px"
          ></video>
        </div>
      </div>
      <div class="analysis-section">
        <h6>AI分析结果</h6>
        <div class="analysis-container">
          <div v-if="analysisResult.analysisScore">
            <div>
              <van-icon name="star" />
              <span class="label">分析得分:</span>
              <span class="value">{{ analysisResult.analysisScore }}</span>
            </div>
            <div class="analysis-item">
              <van-icon name="star" />
              <span class="label">速度得分:</span>
              <span class="value">{{ analysisResult.synthesisSpeed }}</span>
            </div>
            <div class="analysis-item">
              <van-icon name="star" />
              <span class="label">姿态得分:</span>
              <span class="value">{{ analysisResult.synthesisGesture }}</span>
            </div>
            <div class="analysis-item">
              <van-icon name="star" />
              <span class="label">节奏得分:</span>
              <span class="value">{{ analysisResult.synthesisRhythm }}</span>
            </div>
            <div class="analysis-item">
              <van-icon name="star" />
              <span class="label">整体评分:</span>
              <span class="value">{{ analysisResult.totalScore }}</span>
            </div>
            <div class="analysis-item">
              <van-icon name="info" />
              <span class="label">分析建议:</span>
              <span class="AISuggessvalue">{{ analysisResult.analysisMsg }}</span>
            </div>
            <div class="analysis-item">
              <van-icon name="info" />
              <span class="label">AI大模型分析建议:</span>
              <span class="AISuggessvalue">{{ analysisResult.aimodelDescriotion }}</span>
            </div>
            <!-- <div class="analysis-item">
          <van-icon name="clock" />
          <span class="value">{{ analysisResult.analysisTime }}</span>
        </div> -->
          </div>
          <div v-else class="no-ai-result">
            <div class="icon"><van-icon name="warning" /></div>
            <p class="title">暂无分析数据</p>
            <p class="tip">请先上传训练视频进行AI分析</p>
          </div>
        </div>
      </div>

      <div class="teacher-comments">
        <h6>教师评语</h6>
        <div class="teacher-container">
          <div class="comment-item" v-if="teacherComment.teacherFeedback">
            <div class="comment-header">
              <van-icon name="user" /><span class="value">{{ teacherComment.teacherName }}</span>
            </div>
            <div class="comment-content">
              {{ teacherComment.teacherFeedback }}
            </div>
            <span class="time">{{ teacherComment.submissionDate }}</span>
          </div>
          <div v-else class="no-comment">暂无教师评语</div>
        </div>
      </div>
      <van-button
        v-if="homeworkDetail.homeworkFlag !== '2'"
        class="full-btn"
        type="primary"
        @click="submitHomework"
        >提交作业</van-button
      >
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import type { UploaderFileListItem } from 'vant'
import { uploadFile, getFilePath, submitHomeworkRequset } from '@/api/upload'
import { getHomeworkDetail } from '@/api/course'
import { useRoute } from 'vue-router'

const route = useRoute()

const videoTypes = ['mp4', 'wmv', 'avi', 'mpeg']
const imgTypes = ['png', 'jpg', 'jpeg']
const audioTypes = ['mp3']

interface AnalysisResult {
  analysisStatus: string
  analysisProgress: string
  submitPath: string
  analysisVideo: string
  analysisScore: string
  analysisMsg: string
  aimodelDescriotion: string
  synthesisSpeed: string
  synthesisGesture: string
  synthesisRhythm: string
  analysisType: string
  analysisTime: string
  totalScore: string
}

interface TeacherComment {
  teacherName: string
  teacherFeedback: string
  submissionDate: string
}

const homeworkDetail = ref({
  teacherName: '',
  homeworkDeadline: '',
  homeworkContent: '',
  homeworkTitle: '',
  homeworkFilepath: '',
  homeworkId: '',
  homeworkFlag: '', //0：学生未提交 1：学生已提交 2：老师已批改
})
const activeBtn = ref<'original' | 'analyze'>('original')
const videoFile = ref<UploaderFileListItem[]>([])
const videoUrl = ref<string | null>('')
const analysisResult = ref<AnalysisResult>({
  analysisStatus: '',
  analysisProgress: '',
  submitPath: '',
  analysisVideo: '',
  analysisScore: '',
  analysisMsg: '',
  aimodelDescriotion: '',
  synthesisSpeed: '',
  synthesisGesture: '',
  synthesisRhythm: '',
  analysisType: '',
  analysisTime: '',
  totalScore: '',
})
const teacherComment = ref<TeacherComment>({
  teacherName: '',
  teacherFeedback: '',
  submissionDate: '',
})
// 定义对象类型
interface FilePath {
  name: string
  url: string
}
const fileParam = ref<FilePath>({
  name: '',
  url: '',
})
const onUploadVideo = async (items: UploaderFileListItem | UploaderFileListItem[]) => {
  const files = Array.isArray(items) ? items : [items]
  console.log('files', items, items.file)
  if (files.length > 0 && files[0].file) {
    videoUrl.value = URL.createObjectURL(files[0].file)
  }
  const file = items.file as File
  const res = await uploadFile(file)
  fileParam.value = res.data
}
const deleteFile = () => {
  videoUrl.value = null
  videoFile.value = []
  fileParam.value = { name: '', url: '' }
}
const showOriginal = () => {
  activeBtn.value = 'original'
}

const analyzeVideo = () => {
  activeBtn.value = 'analyze'
}
// 根据resourceUrl返回文件类型
function getFileType(url) {
  // 提取文件扩展名（转换为小写以兼容大小写）
  const extension = url.split('.').pop().toLowerCase().split('?')[0] // 处理可能的查询参数

  if (videoTypes.includes(extension)) {
    return 'video'
  } else if (imgTypes.includes(extension)) {
    return 'image'
  } else if (audioTypes.includes(extension)) {
    return 'audio'
  } else {
    return 'unknown'
  }
}
const submitHomework = async () => {
  const res = await getFilePath({ filePath: fileParam.value.url })
  const analysisId = res.data.taskId
  const fileParamArr = fileParam.value.url.split('.')
  const resourceType = fileParamArr[fileParamArr.length - 1]
  const submitRes = await submitHomeworkRequset({
    homeworkId: homeworkDetail.value.homeworkId,
    path: fileParam.value.url,
    analysisId: analysisId,
    resourceType: resourceType,
  })
  // console.log('submitRes', submitRes)
  if (submitRes.code == 200) {
    showSuccessToast('提交成功！')
    getHomework()
  }
}
const getHomework = async () => {
  const id = route.query.id
  const res = await getHomeworkDetail({ id: id })
  const data = res.data.homeworkAnalysisVo
  homeworkDetail.value.teacherName = data.teacherName
  homeworkDetail.value.homeworkDeadline = data.homeworkDeadline
  homeworkDetail.value.homeworkContent = data.homeworkContent
  homeworkDetail.value.homeworkTitle = data.homeworkTitle
  homeworkDetail.value.homeworkFilepath = data.homeworkFilepath
  homeworkDetail.value.homeworkId = data.id
  homeworkDetail.value.homeworkFlag = data.homeworkFlag

  analysisResult.value.analysisProgress = data.analysisProgress
  analysisResult.value.submitPath = data.submitPath
  analysisResult.value.analysisVideo = data.analysisVideo
  analysisResult.value.analysisScore = data.analysisScore
  analysisResult.value.analysisMsg = data.analysisMsg.replace(/\*/g, '')
  analysisResult.value.aimodelDescriotion = data.aimodelDescriotion.replace(/\*/g, '')
  analysisResult.value.synthesisSpeed = data.synthesisSpeed
  analysisResult.value.synthesisGesture = data.synthesisGesture
  analysisResult.value.synthesisRhythm = data.synthesisRhythm
  analysisResult.value.analysisType = data.analysisType
  analysisResult.value.analysisTime = data.analysisTime
  analysisResult.value.analysisStatus = data.analysisStatus

  teacherComment.value.teacherName = data.teacherName
  teacherComment.value.teacherFeedback = data.teacherFeedback
  teacherComment.value.submissionDate = data.submissionDate

  videoUrl.value = data.submitPath
}
onMounted(() => {
  getHomework()
})
</script>

<style scoped lang="scss">
.container {
  padding: 10px;
}
.courses {
  padding: 10px;
  border-radius: 10px;
  background: linear-gradient(0deg, rgba(0, 0, 0, 0.001), rgba(0, 0, 0, 0.001)), #ffffff;
  box-shadow: 0px 1px 2px 0px rgba(0, 0, 0, 0.05);
  .practice-details {
    .practice-content {
      color: #6b7280;
      font-size: 12px;
      margin-top: 10px;
      .time {
        margin-top: 10px;
        .van-icon-clock {
          margin-right: 3px;
        }
        .van-icon-user {
          margin-left: 8px;
          margin-right: 3px;
        }
      }
    }
  }
}

.example-video {
  .label {
    color: #374151;
    // font-weight: bolder;
    font-size: 14px;
    line-height: 40px;
  }
  .video-tip {
    font-size: 12px;
    color: #6b7280;
  }
}
video {
  border-radius: 5px;
}
.activity {
  margin-top: 20px;
  padding: 10px;
  .video-upload {
    margin-top: 10px;
    .upload-title {
      display: flex;
      justify-content: space-between; /* 这将使子元素分别靠左和靠右 */
      align-items: center; /* 垂直居中 */
      width: 100%;
      .label {
        color: #374151;
        font-size: 14px;
      }
      .video-actions {
        // float: right;
        display: flex;
        gap: 8px; /* 给按钮之间添加一些间距 */
        .active-btn {
          color: #2563eb;
          background: #dbeafe;
        }
      }
    }
  }
  .upload-container {
    position: relative;
    .van-icon-cross {
      position: absolute;
      font-size: 20px;
      right: 0px;
      top: 22px;
      color: rgb(251, 250, 250);
      z-index: 99;
    }
  }
}
:deep(.van-uploader) {
  margin: 10px 0;
  width: 100%;
  .van-uploader__upload {
    width: 100%;
    border-radius: 5px;
  }
}
.analysis-section {
  margin-top: 10px;
  .analysis-container {
    margin-top: 10px;
    padding: 10px;
    border-radius: 5px;
    background: #f9fafb;
  }
  .label {
    font-size: 14px;
    color: #374151;
  }
  .value {
    font-size: 14px;
    color: #6b7280;
  }
  .AISuggessvalue {
    display: block;
    font-size: 14px;
    color: #6b7280;
    white-space: pre-line;
  }
  .van-icon-star {
    font-size: 14px;
    color: #ffd21e;
    margin-right: 5px;
  }
  .van-icon-info,
  .van-icon-clock {
    font-size: 14px;
    color: #3b82f6;
    margin-right: 5px;
  }
  .no-ai-result {
    margin: 10px 0;
    padding: 20px;
    display: flex;
    // justify-content: center;
    flex-direction: column;
    align-items: center;
    gap: 10px;
    background-color: #f7f8fa;
    border-radius: 5px;
    .van-icon-warning {
      color: #dcdee0;
    }
    .title {
      color: #6b7280;
      font-size: 14px;
    }
    .tip {
      color: #9ca3af;
      font-size: 12px;
    }
  }
}
.full-btn {
  margin: 10px 0;
  width: 100%;
}
.teacher-comments {
  margin-top: 10px;
  .teacher-container {
    margin-top: 10px;
    padding: 10px;
    border-radius: 5px;
    background: #f9fafb;
  }
  .van-icon-user {
    font-size: 14px;
    color: #3b82f6;
    margin-right: 5px;
  }
  .van-icon-clock {
    font-size: 14px;
    color: #6b7280;
    margin-left: 5px;
    margin-right: 5px;
  }
  .time {
    font-size: 14px;
  }
  .comment-content {
    margin: 10px 0;
    color: #6b7280;
    font-size: 14px;
  }
  .no-comment {
    margin: 10px 0;
    color: #6b7280;
    font-size: 14px;
  }
  .value {
    font-size: 14px;
    color: #6b7280;
  }
}
</style>
